//
//  CandyTableViewController.m
//  CandySearch
//
//  Created by Mac on 13-12-25.
//  Copyright (c) 2013年 Mac. All rights reserved.
//

#import "CandyTableViewController.h"
#import "Candy.h"

@implementation CandyTableViewController

@synthesize candyArray;
@synthesize filteredCandyArray;
@synthesize candySearchBar;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    // 在用户使用搜索栏前隐藏范围栏。
    [candySearchBar setShowsScopeBar:NO];
    [candySearchBar sizeToFit];
    [super viewDidLoad];
    
    // 将搜索栏藏起来（搜索栏只有在用户滚动到列表视图顶端时才会出现）
    CGRect newBounds = self.tableView.bounds;
    newBounds.origin.y = newBounds.origin.y + candySearchBar.bounds.size.height;
    self.tableView.bounds = newBounds;
    
    candyArray = [NSArray arrayWithObjects:
                  [Candy candyofCategory:@"chocolate" name:@"chocolate bar"],
                  [Candy candyofCategory:@"chocolate" name:@"chocolate chip"],
                  [Candy candyofCategory:@"chocolate" name:@"dark chocolate"],
                  [Candy candyofCategory:@"hard" name:@"lollipop"],
                  [Candy candyofCategory:@"hard" name:@"candy cane"],
                  [Candy candyofCategory:@"hard" name:@"jaw breaker"],
                  [Candy candyofCategory:@"other" name:@"caramel"],
                  [Candy candyofCategory:@"other" name:@"sour chew"],
                  [Candy candyofCategory:@"other" name:@"peanut butter cup"],
                  [Candy candyofCategory:@"other" name:@"gummi bear"],nil];
    //初始化filteredCandyArray数组，使它和candyArray数组的大小一样
    self.filteredCandyArray = [NSMutableArray arrayWithCapacity:[candyArray count]];

    //刷新tableView列表
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

-(IBAction)goToSearch:(id)sender {
    // 如果你担心用户无法发现藏在列表顶端的搜索栏，那我们在导航栏加一个搜索图标。
    // 如果你不隐藏搜索栏，那就别加入这个搜索图标，否则就重复了。
    [candySearchBar becomeFirstResponder];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //返回candyArray数组的长度
//    return [candyArray count];
    //检查现在显示的是哪个类表视图，然后返回响应的数组长度
    if (tableView == self.searchDisplayController.searchResultsTableView){
        return [filteredCandyArray count];
    }else {
        return [candyArray count];
    }
}

//搜索栏处理 -- 过滤内容的函数
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    //根据搜索栏的内容喝范围更新过滤后的数组
    //先将过滤后的数组清空
    [self.filteredCandyArray removeAllObjects];
    //用NSPredicate来过滤数组
    //@"SELF.name contains[c] %@" 解释：SELF.name指的是数组中每一个Candy对象的“name”属性、contains[c]会让predicate搜索“name”属性中的字符串，看看有没有喝后面提供的“searchText”一样的字符串。大小写有别.
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
//    filteredCandyArray = [NSMutableArray arrayWithArray:[candyArray filteredArrayUsingPredicate:predicate]];
    NSArray *tempArray = [candyArray filteredArrayUsingPredicate:predicate];
    if (![scope isEqualToString:@"All"]) {
        // 进一步用糖果类别来过滤数据
        NSPredicate *scopePredicate = [NSPredicate predicateWithFormat:@"SELF.category contains[c] %@",scope];
        tempArray = [tempArray filteredArrayUsingPredicate:scopePredicate];
    }
    filteredCandyArray = [NSMutableArray arrayWithArray:tempArray];
}
//SearchText的代理 -- 用户函数搜索懒里的字符串时就会被调用
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //当用户改变搜索字符串时，让列表的数据来源重新加载数据
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    //返回YES，让table view 重新加载.
    return YES;
}

//SearchText的代理 -- 范围栏改变时被调用
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    //当用户改变搜索范围时，让列表的数据来源重新加载数据
    [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    //返回YES,让table view重新加载
    return YES;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //创建一个Candy对象
    Candy *candy = nil;
//    candy = [candyArray objectAtIndex:indexPath.row];
    //检查现在应该显示普通列表还是过滤后的列表
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        candy = [filteredCandyArray objectAtIndex:indexPath.row];
    }else {
        candy = [candyArray objectAtIndex:indexPath.row];
    }
    //设置列表的一行
    cell.textLabel.text = candy.name;
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"candyDetail"]){
        UIViewController *candyDetailViewController = [segue destinationViewController];
        //我们需要知道哪个是现在在显示的列表视图，这样才能从相应的数组中提取正确的信息，显示在详细视图中。
        if (sender == self.searchDisplayController.searchResultsTableView) {
            NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
            NSString *destinationTitle = [[filteredCandyArray objectAtIndex:[indexPath row]]name];
            [candyDetailViewController setTitle:destinationTitle];
        }else {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
            NSString *destinationTitle = [[candyArray objectAtIndex:[indexPath row]]name];
            [candyDetailViewController setTitle:destinationTitle];
        }
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //切入详细视图
    [self performSegueWithIdentifier:@"candyDetail" sender:tableView];
}

@end
